const Controllers = require('../controllers/Controller.js').controller;
const app = getApp();
function InitTime(endtime){
    var dd,hh,mm,ss = null;
    var time = (new Date(endtime).getTime() - new Date().getTime())/1000;
    if(time<=0){
        return '结束'
    }else{
        dd = Math.floor(time / 60 / 60 / 24);
        hh = Math.floor((time / 60 / 60) % 24);
        mm = Math.floor((time / 60) % 60);
        ss = Math.floor(time  % 60);
        var str = dd+"天"+hh+":"+mm+":"+ss;
        return str;
    }
}
Page({
  data: {
    globalStype:'',
    isShow:false,
    goodsId:'',
    goodsDetailsdata:'',
    shopDetailsdata:'',
    myInformationdata:'',
    goodsnumber:1,
    iscollect:false,
    confirmcartdata:'',
    confirmtype:'cart',
    cartNum:0,
    imgheights: [],
    //图片宽度 
    imgwidth: 750,
    //默认  
    current: 0,
    imgList2:[],
    marketid:'',
    marketNo:'',
    backbool:true,
  },
  onLoad: function (option) {
    this.setData({globalStype:app.globalData.globalStype})
    if(option.id){
      this.setData({
        goodsId:option.id
      })
      this.goodsDetails()
    }
    let shopId=''
    if(app.globalData.shopId){
      shopId=app.globalData.shopId
    }
    if(option.shopId){
      shopId=option.shopId
      app.globalData.shopId=option.shopId
    }
    if(wx.getStorageSync('shopId')){
      shopId=wx.getStorageSync('shopId')
      app.globalData.shopId=shopId
    }
    this.setData({
      shopId,
      myInformationdata:app.globalData.myshopinfo
    })

    if(getCurrentPages().length<=1){
      this.setData({
        backbool:false
      })
    }else{
      this.setData({
        backbool:true
      })
    }
  },
  onShow(){
    if (wx.getStorageSync('usertoken')) {
        //加载首页数据
        this.myInformation()
        this.iscollect()
        this.cartNum()
    }
    //无usertoken，等待login登录回调
    app.usertokenReadyCallback = res => {
      if(res.data.sessionId){
        this.myInformation()
        this.iscollect()
        this.cartNum()
      }
    }
    
  },
  swiperChange: function (e) {
    var that = this;
  },
  myInformation(){
    //获取数据
    Controllers.myInformation({shopId:this.data.shopId}).then(res => {
      this.setData({
        myInformationdata:res.data.accountRelation
      })
      app.globalData.myshopinfo=res.data.accountRelation
    })
  },
  imageLoad: function (e) {//获取图片真实宽度  
    var imgwidth = e.detail.width,
      imgheight = e.detail.height,
      //宽高比  
      ratio = imgwidth / imgheight;
      console.log(imgwidth, imgheight)
    //计算的高度值  
    var viewHeight = 750 / ratio;
    var imgheight = viewHeight;
    var imgheights = this.data.imgheights;
    //把每一张图片的对应的高度记录到数组里  
    imgheights[e.target.dataset.id] = imgheight;
    this.setData({
      imgheights: imgheights
    })
  },
  bindchange: function (e) {
    // console.log(e.detail.current)
    this.setData({ current: e.detail.current })
  },
  goodsDetails(){
    //获取数据
    Controllers.goodsDetails({goodsId:this.data.goodsId}).then(res => {
      // res.data.rotationImgs=res.data.rotationImgs.split('/')
      if(res.data.labelName)
      res.data.labelName=res.data.labelName.split('/')
      // res.data.detailImgs=res.data.detailImgs.split('/')
      this.setData({
        goodsDetailsdata:res.data
      })
      if(this.data.goodsDetailsdata.newPinAccount && this.data.goodsDetailsdata.newPinAccount.endTime){
          var that=this;
          setInterval(()=> {
            this.data.goodsDetailsdata.newPinAccount.downtime=InitTime(this.data.goodsDetailsdata.newPinAccount.endTime.replace(/-/g, '/'))
            this.setData({
              goodsDetailsdata:this.data.goodsDetailsdata
            })

          }, 1000);
      }
    
      
      this.shopDetails()
      
      
    })
  },
  shopDetails(){
    //获取数据
    Controllers.shopDetails({shopId:this.data.shopId}).then(res => {
      this.setData({
        shopDetailsdata:res.data
      })

    })
  },
  cartNum(){
    Controllers.cartNum({shopId:this.data.shopId}).then(res => {
      this.setData({
        cartNumdata:res.data
      })

    })
  },
  
  calling(e){
    app.calling(e.currentTarget.dataset.phone)
  },
  onShareAppMessage: function( options ){
      let title = this.data.goodsDetailsdata.name || '商品详情页';
      let imageUrl = this.data.goodsDetailsdata.rotationImgs[0] || '';
      let path='/pages/Index/Detail?id='+this.data.goodsId +'&shopId='+this.data.shopId
  　　var that = this;
  　　// 设置菜单中的转发按钮触发转发事件时的转发内容
  　　var shareObj = {
  　　　　title: title,
  　　　　path: path,
  　　　　imageUrl: imageUrl
  　　};
  　　// 来自页面内的按钮的转发
  　　if( options.from == 'button' ){
  　　　　var eData = options.target.dataset;
  　　　　console.log( eData.name );     // shareBtn
  　　　　// 此处可以修改 shareObj 中的内容
  // 　　　　shareObj.path = '/pages/btnname/btnname?btn_name='+eData.name;
  　　}
  　　// 返回shareObj
  　　return shareObj;
  },
  plus(){
    if (!wx.getStorageSync('usertoken')) {
        app.GetLogin()
        return
    }
    var nums=this.data.goodsnumber+1;
    this.setData({
      goodsnumber:nums
    })
  },
  mins(){
    if (!wx.getStorageSync('usertoken')) {
        app.GetLogin()
        return
    }
    if(this.data.goodsnumber>1){
      var nums=this.data.goodsnumber-1;
      this.setData({
        goodsnumber:nums
      })
    }
  },
  changenums(e){
    if (!wx.getStorageSync('usertoken')) {
        app.GetLogin()
        return
    }
    if(this.data.goodsnumber<1){
      this.setData({
        goodsnumber:1
      })
    }else{
      this.setData({
        goodsnumber:e.detail.value
      })
    }
  },
  collect(){
    if (!wx.getStorageSync('usertoken')) {
        app.GetLogin()
        return
    }
    Controllers.controllerGoods({goodsId:this.data.goodsId,shopId:this.data.shopId}).then(res => {
      this.setData({
        iscollect:res.data
      })
      if(res.data){
        wx.showToast({
          title: '收藏成功！',
          icon: 'none'
        })
      }else{
        wx.showToast({
          title: '取消收藏成功！',
          icon: 'none'
        })
      }
    })
  },
  iscollect(){
    Controllers.goodsIsController({goodsId:this.data.goodsId}).then(res => {
      this.setData({
        iscollect:res.data
      })
    })
  },
  gocart(){
    if (!wx.getStorageSync('usertoken')) {
        app.GetLogin()
        return
    }
    wx.navigateTo({
      url:'/pages/cart/index/index?isReturn=1'
    })
  },

  gogroup(e){
    let pin=e.currentTarget.dataset.pin;
    if(pin==1){
      this.setData({
        isPin:true
      })
    }else{
      this.setData({
        isPin:false
      })
    }
    if (!wx.getStorageSync('usertoken')) {
        app.GetLogin()
        return
    }
    let that=this

    wx.requestSubscribeMessage({
      tmplIds:['4RdGGbKzw3AynLXPpyznfiIznGB0piSldaAoyW1iVqI','mq8pXj6Wdv5zuTh2kZxcmdon1UYR84459q8crHtxh8w','lxKzUnwW5Q_5hI8u3-T8hAFjO6BSNSTs9GA47xBbmk0'],
      success:res=>{
        console.log(res)
      },
      complete:()=>{
        if (!wx.getStorageSync('usertoken')) {
          app.ToLoginlink()
          return
        }

        let goods={};
        goods=that.data.goodsDetailsdata
        goods.shopId=that.data.shopId
        goods.goodsId=that.data.goodsId
        goods.isPin=that.data.isPin
        // goods.num=this.data.goodsnumber
        let marketid=e.currentTarget.dataset.id
        that.goodsSettlement(goods,marketid,'')

      }
    })

    
    // if(this.data.goodsDetailsdata.type==0){
    //   this.goodsSettlement(goods,marketid,'')
    // }else{
    //   this.setData({
    //     confirmcartdata:goods,
    //     marketid:marketid,
    //     confirmtype:"group",
    //     isShow:true
    //   })
    // }
  },
  gogroupno(e){
    let pin=e.currentTarget.dataset.pin;
    if(pin==1){
      this.setData({
        isPin:true
      })
    }else{
      this.setData({
        isPin:false
      })
    }
    if (!wx.getStorageSync('usertoken')) {
        app.GetLogin()
        return
    }
    let goods={};
    goods=this.data.goodsDetailsdata
    goods.shopId=this.data.shopId
    goods.goodsId=this.data.goodsId
    goods.isPin=this.data.isPin
    goods.content=""
    // goods.num=this.data.goodsnumber
    let marketNo=e.currentTarget.dataset.id
    this.goodsSettlement(goods,'',marketNo)
    // if(this.data.goodsDetailsdata.type==0){
    //   this.goodsSettlement(goods,'',marketNo)
    // }else{
    //   this.setData({
    //     confirmcartdata:goods,
    //     confirmtype:"groupno",
    //     marketNo:marketNo,
    //     isShow:true
    //   })
    // }
  },
  addcart(){
    if (!wx.getStorageSync('usertoken')) {
        app.GetLogin()
        return
    }
    let goods={};
    goods=this.data.goodsDetailsdata
    goods.shopId=this.data.shopId
    goods.goodsId=this.data.goodsId
    // goods.num=this.data.goodsnumber
    this.setData({
      confirmcartdata:goods,
      isShow:true
    })
  },
  closecart(){
    this.setData({
      isShow: false
    })
  },
  appointment(){
    let that=this
    wx.requestSubscribeMessage({
      tmplIds:['Gc_gkdb1wX-cSBFPD4D5D31w6ZOojJeDckkzo49pBmQ','FKMu-6I96hfuWhGpwb-JxdAKmtI1j013G4GTy2rz7Ms','hD6D4MmAd2JDgrivAhrWDoOXweER5uf9ONSwryEXVe0'],
      success:res=>{
        console.log(res)
      },
      complete:()=>{
        if (!wx.getStorageSync('usertoken')) {
          app.GetLogin()
          return
        }
        if(that.data.myInformationdata.vip==0 && that.data.goodsDetailsdata.vip==1){
          wx.showToast({
            title: 'VIP专享，请注册为会员！',
            icon: 'none'
          })
        }else{
          wx.navigateTo({
            url:'/pages/Index/Service?id='+that.data.goodsId
          })
        }
      }
    })
  },
  confirmcart(e){
    let pin=e.currentTarget.dataset.pin;
    if(pin==1){
      this.setData({
        isPin:true
      })
    }else{
      this.setData({
        isPin:false
      })
    }
    if (!wx.getStorageSync('usertoken')) {
        app.GetLogin()
        return
    }
    let goods=this.data.confirmcartdata;
    goods.num=this.data.goodsnumber
    goods.isPin=this.data.isPin
    if(this.data.confirmtype=='group'){
      this.goodsSettlement(goods,this.data.marketid,'')
    }else if(this.data.confirmtype=="groupno"){
      this.goodsSettlement(goods,'',this.data.marketNo)
    }else{
      this.addGoods(goods)
    }
  },
  goodsSettlement(goods,marketid,marketNo){
    if (!wx.getStorageSync('usertoken')) {
        app.GetLogin()
        return
    }
    var goods=goods;
    delete goods.content;
    if(this.data.myInformationdata.vip==0 && this.data.goodsDetailsdata.vip==1){
        wx.showToast({
          title: 'VIP专享，请注册为会员！',
          icon: 'none'
        })
    }else{
      if(marketid){
        let data={
          shopId:this.data.shopId,
          goodsId:this.data.goodsId,
          marketId:marketid
        }

        Controllers.createMarket(data).then(res => {
            let no=res.data.no
            console.log(goods)
            wx.navigateTo({
              url:'/pages/cart/submitOrder/submitOrder?good='+ encodeURIComponent(JSON.stringify(goods)) +'&isGood=true&marketNo='+ no
            })
        })
      }else if(marketNo){
        let no=marketNo
        console.log(goods)
        wx.navigateTo({
          url:'/pages/cart/submitOrder/submitOrder?good='+ encodeURIComponent(JSON.stringify(goods)) +'&isGood=true&marketNo='+ no
        })
      }else{
        console.log(goods)
        wx.navigateTo({
          url:'/pages/cart/submitOrder/submitOrder?good='+ encodeURIComponent(JSON.stringify(goods)) +'&isGood=true'
        })
      }
      
    }
  },
  goorder(e){
    let pin=e.currentTarget.dataset.pin;
    if(pin==1){
      this.setData({
        isPin:true
      })
    }else{
      this.setData({
        isPin:false
      })
    }
    let that=this
    wx.requestSubscribeMessage({
      tmplIds:['4RdGGbKzw3AynLXPpyznfiIznGB0piSldaAoyW1iVqI','mq8pXj6Wdv5zuTh2kZxcmdon1UYR84459q8crHtxh8w','lxKzUnwW5Q_5hI8u3-T8hAFjO6BSNSTs9GA47xBbmk0'],
      success:res=>{
        console.log(res)
      },
      complete:()=>{
        if (!wx.getStorageSync('usertoken')) {
          app.GetLogin()
          return
        }
        let goods={};
        goods=that.data.goodsDetailsdata
        goods.shopId=that.data.shopId
        goods.goodsId=that.data.goodsId
        goods.isPin=that.data.isPin
        goods.num=that.data.goodsnumber
        console.log(goods);
        that.goodsSettlement(goods,'','')
      }
    })
  },
  addGoods(data){
    if (!wx.getStorageSync('usertoken')) {
        app.GetLogin()
        return
    }
    if(this.data.myInformationdata.vip==0 && this.data.goodsDetailsdata.vip==1){
        wx.showToast({
          title: 'VIP专享，请注册为会员！',
          icon: 'none'
        })
    }else{
      let goods=this.data.goodsDetailsdata;
      let data={}
      data.goodsId=goods.goodsId;
      data.num=this.data.goodsnumber;
      data.shopId=goods.shopId;
      Controllers.addGoods(data).then(res => {
        wx.showToast({
          title: '加入购物车成功！',
          icon: 'none',
          duration: 1000
        })
        this.setData({
          isShow: false
        })
      })
    }
  },

  preview(event) {
    let currentUrl = event.currentTarget.dataset.src
    let lists=[]
    for(let item of event.currentTarget.dataset.lists){
      lists.push(item.image)
    }
    wx.previewImage({
      current: currentUrl, // 当前显示图片的http链接
      urls: lists // 需要预览的图片http链接列表
    })
  },
  backindex(e){
    let page=getCurrentPages()
    let shopId=this.data.shopId
    console.log(page.length)
    if(page.length<=1){
      wx.redirectTo({
        url: '/pages/Index/Index?shopId='+shopId,
      })
    }
  }
})